//
//  ScanViewController.m
//  FVQuickMessage
//
//  Created by dllo on 16/8/12.
//  Copyright © 2016年 zty. All rights reserved.
//

#import "ScanViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <objc/runtime.h>
#import "FriendViewController.h"

@interface ScanViewController ()<AVCaptureMetadataOutputObjectsDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate>

@property (nonatomic, retain) AVCaptureSession *session;
@property (nonatomic, retain) AVCaptureVideoPreviewLayer *previewLayer;

@end

@implementation ScanViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self config];
    
    [self isOnorOffCamera];
    
    // Do any additional setup after loading the view.
}

-(void)config {
    
    self.view.backgroundColor = [UIColor blackColor];
    self.navigationItem.title = @"扫一扫";
    self.navigationController.navigationBar.barTintColor = [UIColor blackColor];
    
}

#pragma mark 判断是否有摄像头
-(void)isOnorOffCamera {
    
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    NSError *error = nil;
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
    if (error) {
        input = nil;
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"未检测到相机" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            [self.navigationController popViewControllerAnimated:YES];
            
        }];
        
        [alert addAction:action];
        [self presentViewController:alert animated:YES completion:^{
            
            
        }];
        
    } else {
        
        [self createSubView];
        
    }
    
}

#pragma mark 设置扫描功能
-(void)createSubView {
    
    CGRect scaneBounds = [UIScreen mainScreen].bounds;
    self.view.frame = scaneBounds;
    
    CGRect viewFrame = self.view.frame;
    CGSize viewSize = CGSizeMake(viewFrame.size.width - 80, viewFrame.size.width - 80);
    
    // 实例化摄像头设备
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    NSError *error = nil;
    
    // 设置输入
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
    
    // 设置输出
    AVCaptureMetadataOutput *outPut = [[AVCaptureMetadataOutput alloc] init];
    CGRect scanCrop = CGRectMake((viewFrame.size.width - viewSize.width) / 2, (viewFrame.size.height - viewSize.height) / 2, viewSize.width, viewSize.height);
    
    // 设置扫描范围
    outPut.rectOfInterest = CGRectMake(scanCrop.origin.y / viewFrame.size.height, scanCrop.origin.x / viewFrame.size.width, scanCrop.size.height / viewFrame.size.height, scanCrop.size.width / viewFrame.size.width);
    
    // 设置输出代理
    [outPut setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    // 拍摄会话
    AVCaptureSession *session = [[AVCaptureSession alloc] init];
    session.sessionPreset = AVCaptureSessionPreset640x480;
    
    // 添加session的输入和输出
    [session addInput:input];
    [session addOutput:outPut];
    
    // 设置输出的格式
    [outPut setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];
    
    // 设置预览图层
    AVCaptureVideoPreviewLayer *preview = [AVCaptureVideoPreviewLayer layerWithSession:session];
    
    // 设置preview图层的属性
    [preview setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    
    // 设置preview图层的大小
    [preview setFrame:self.view.bounds];
    
    // 将图层添加到视图的图层
    [self.view.layer insertSublayer:preview atIndex:0];
    self.previewLayer = preview;
    
    self.session = session;
    
}

-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
    
    NSString *stringValue;
    if ([metadataObjects count] > 0) {
        [_session stopRunning];
        
        AVMetadataMachineReadableCodeObject *metadataObject = [metadataObjects objectAtIndex:0];
        stringValue = metadataObject.stringValue;
        
        FriendViewController *friendVC = [[FriendViewController alloc] init];
        
        friendVC.userName = stringValue;
        
        [self.navigationController pushViewController:friendVC animated:YES];
        
    }
    
}

-(void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    [self.session startRunning];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
